;
(function(w) {

  new Vue({
    el: '#businessDispatch',
    data: {
      listMenu: [
        {
          name: '待分派',
          code: 'WFP',
          num: 0
        },
        {
          name: '已分派',
          code: 'YFP',
          num: 0
        }
      ],
      selectedListMenuCode: [],
      keyWord: null,
      columns: '',
      orders: '',
      rperson: {
        name: null,
        list: [],
        id: null
      }, // 对接人
      totalPage: 0,
      totalCount: 0,
      currentPage: 1,
      limit: ['10'],
      pageCounts: [{
        name: '10',
        code: '10'
      }, {
        name: '15',
        code: '15'
      }, {
        name: '20',
        code: '20'
      }],
      totalCount: 0,
      channelType: [], //渠道分类
      selectedChannelType: [],
      allChannelName: [],
      channelName: [], //渠道名称
      selectedChannelName: [],
      sourceList: [], //商机来源
      selectedSource: [],
      positionList: [],
      personList: [],
      listData: [],
      countInfoData: [],
      excelURI: 'javascript:;',
      isShowPersonLayer: false,
      isShowSelector: false,
      selectedMulItem: {
        sjIds: [],
        id: null,
        name: null
      },
      assigneeIdArr: [],
      isAllSelected: false,
      quanxian: localStorage.getItem('permissions'),
      isExtenseFlag: false,

      //自定义开始
      configType: 'WZ', //默认完整WZ     JD简单，WZ完整，自定义配置PZ
      module: '#',
      headArr: [],
      sortTableTitle: [],
      isScroll: false,
      isShowTableLayer: false,
      dateTimeUpdate: ['createTime'],
      isActiveCode: '#',
      tbTitleWidth:{},
      listObj:{
        bizOpptAssigns:[]
      },
			industryType: [],
			selectedIndustryType: [],
    },
    filters: {
      formatYYYYMMddHHmm(item) {
        if (!item) return '--'
        return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm')
      },
      formatIntentLevel: function(item) {
        if (!item) return '--'
        return hlCodeConvert.businessFollowIntentLevel(item)
      },
      formatUndefined: function(item) {
        if (!item) return '--'
        if (typeof item == 'number') {
          if (!isNaN(item) && item.toString().length == 13) {
            return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm')
          };
        }
        return item
      },
    },
    computed: {

    },
    methods: {
      selectMenuList(){
        this.currentPage = 1
        this.searchData()
      },
       // 表头中是否全选方法
      isAllSelect(item){
        if(this.selectedMulItem.sjIds.length == this.listObj.bizOpptAssigns.length){
          this.selectedMulItem.sjIds = []
        } else {
          this.selectedMulItem.sjIds = []
          this.listObj.bizOpptAssigns.map(item => {
            this.selectedMulItem.sjIds.push(item.sjId)
          })
        }
      },
      // 单个选择
      selectDispatchItem(item) {
        let num = this.selectedMulItem.sjIds.indexOf(item)
        if (num == -1) {
          this.selectedMulItem.sjIds.push(item)
        } else {
          this.selectedMulItem.sjIds.splice(num, 1)
        }
      },
      // 获取当前用户所在的岗位列表
      getUserPositions() {
        hlhttp.get({
          url: 'organization/user_positions',
          data: {
            show_suborg: 'Y'
          },
          success: data => {
            this.positionList = data;
          }
        })
      },
      // 操作区分派按钮方法
      dispatchBusiness(id) {
        this.selectedMulItem.sjIds.push(id);
        this.isShowPersonLayer = true;
        this.selectedMulItem.id = ''
        this.selectedMulItem.name = ''
        this.personList = []
        $('.org-name').html('请选择')
        $('.person-name').html('请选择')
      },
      closePersonLayer() {
        this.isShowPersonLayer = false;
        this.selectedMulItem.sjIds = []
        this.selectedMulItem.id = ''
        this.selectedMulItem.name = ''
      },
      singleItemSelectProject(item) {
        var that = this;
        hlhttp.get({
          url: 'organization/admin_position_users',
          data: {
            'position_id': item.positionId,
            'is_admin': item.isAdmin
          },
          success: data => {
            that.personList = data;
            that.selectedMulItem.name = ''
            that.selectedMulItem.id = '';
            that.$refs.DJR.innerHTML = '请选择'
          }
        })
      },
      singleItemSelectPerson(item) {
        this.selectedMulItem.id = item.userId;
        this.selectedMulItem.name = item.userName;
      },
      // 确定分派的方法
      confirmDispatchSingleItem() {
        if (!this.selectedMulItem.id) {
          hl.toast('请选择对接人')
          return
        }
        if (!this.selectedMulItem.sjIds.length) {
          hl.toast('请选择线索')
          return
        }
        hlhttp.put({
          url: 'customer/biz_oppt_assign',
          data: {
            sj_ids: this.selectedMulItem.sjIds.join(','),
            assignee_id: this.selectedMulItem.id,
            assignee_name: this.selectedMulItem.name
          },
          success: data => {
            hl.toast('分派成功')
            this.isShowPersonLayer = false;
            this.isShowSelector = false;
            this.selectedMulItem.sjIds = []
            this.selectedMulItem.id = ''
            this.selectedMulItem.name = ''
            this.search()
          }
        })
      },
      // 批量分派按钮
      batchDispatch() {
        this.isShowSelector = !this.isShowSelector
        this.personList = []
        this.selectedMulItem = {
          sjIds: [],
          id: '',
          name: ''
        }
        this.getUserPositions();
      },
      // 去详情
      goTodetail(id) {
        hlUrlUtil.goTo('businessDetails', {
          'businessId': id,
          'page': 'businessDispatch',
          'ddtab': true
        }, true)
      },
      resetTabbar(){
        this.selectedListMenuCode = []
        this.currentPage = 1
        this.searchData()
      },
      openSearch: function() {
        if (this.isExtenseFlag == true) {
          this.isExtenseFlag = false;
          return false;
        }
        if (this.isExtenseFlag == false) {
          this.isExtenseFlag = true;
          return false;
        }
      },
      search() {
        this.currentPage = 1;
        this.limit = ['10'];
        this.searchData()
      },
      reset() {
        this.keyWord = null;
        this.orders = '';
        this.isActiveCode = '';
        this.columns = '';
        this.selectedSource = []
        this.selectedChannelType = []
        this.selectedChannelName = []
				this.selectedIndustryType = []

        this.rperson = {
          name: null,
          list: [],
          id: null
        };
        this.search()
      },
      // 获取对接人人员列表
      getRpersonData() {
        var self = this;
        hlhttp.get({
          url: 'data_group/users/_search',
          data: {
            'keyword': self.rperson.name || '#'
          },
          success: function(data) {
            self.rperson.list = data;
            // 自动匹配  当输入的名字跟下拉列表中名字匹配时  则存储ID
            data.forEach(el => {
              if (self.rperson.name.match(el.userName)) self.rperson.id = el.userId;
            })
          }
        })
      },
      getMatchRperson() {
        this.getRpersonData()
      },
      // 设置对接人name，获取id
      setRperson(name, id) {
        this.rperson = {
          name: name,
          list: [],
          id: id
        }
      },
      hideRpersonList() {
        this.rperson.list = [];
      },
      // 渠道分类
      getChannelType() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH',
            config_name: 'ZS_CHANNEL_CATE'
          },
          success: data => {
            this.channelType = hlArrayUtil.replaceData(data, [{key: 'dictName', rKey: 'name'}, {key: 'dictCode', rKey: 'code'}]);
          }
        })

      },
      selectChannelType(arr) {
        this.selectedChannelType = [arr[0].code]
        this.getChannelName()
      },
      // 获取渠道名称
      getChannelName() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH',
            config_name: 'ZS_CHANNEL_NAME',
        		parent_dict_code: this.selectedChannelType[0]
          },
          success: data => {
            this.channelName = hlArrayUtil.replaceData(data, [{key: 'dictName', rKey: 'name'}, {key: 'dictCode', rKey: 'code'}]);
          }
        })

      },
      selectChannelName(arr) {
        this.selectedChannelName = [arr[0].code]
      },
      //商机来源
      getSJsource() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH0SHJI',
            config_name: 'SJ_SOURCE'
          },
          success: data => {
            data.unshift({
              'dictName': '全部',
              'dictCode': '#'
            })
            this.sourceList = hlArrayUtil.replaceData(data, [{key: 'dictName', rKey: 'name'}, {key: 'dictCode', rKey: 'code'}]);
          }
        })
      },
      selectSJsource(arr) {
        this.selectedSource = [arr[0].code]
      },
      selectPerNum(arr) {
        this.limit = [arr[0].code]
        this.currentPage = 1
        this.searchData()
      },
      sortBySTTime(item) {
        if (this.dateTimeUpdate.indexOf(item.value) == -1) return
        this.isActiveCode = item.value;
        this.orders = this.orders == 'ASC' ? 'DESC' : 'ASC';
        this.columns = item.orderName
        this.currentPage = 1
        this.searchData()
      },
      //获取自定义表头配置状态
      configTypeDt() {
        hlhttp.get({
          url: 'configure/customize_column_header/type',
          data: { module: 'ZHSH_XSFP' },
          success: (data) => {
            this.configType = data.configType;
            this.customizeHeaderDt()
          }
        })
      },

      searchData() {
        var self = this;
        var submitData = {
          'keyword': self.keyWord || '#',
          'assignee_id': self.rperson.id || '#',
          'channel_category_code': self.selectedChannelType.length ? self.selectedChannelType[0] : '#',
          'channel_name_code': self.selectedChannelName.length ? self.selectedChannelName[0] : '#',
          'origin': self.selectedSource.code || '#',
          'assign_status': self.selectedListMenuCode.length ? self.selectedListMenuCode.join(',') : '#',
					'industry': self.selectedIndustryType.length ? self.selectedIndustryType + '' : '#',
          'limit': self.limit[0],
          'page': self.currentPage,
          'columns': self.columns || '#',
          'orders': self.orders || '#',
        }

        hlhttp.get({
          url: 'customer/biz_oppt_assign_search',
          data: submitData,
          success: function(data) {
            data.bizOpptAssigns.map(item => {
              item.iSselect = true
            })
            self.listObj = data
            data.bizOpptAssigns.forEach(el => el['isChecked'] = 'N')
            self.listData = data.bizOpptAssigns
            self.totalPage = data.totalPage
            self.totalCount = data.totalCount
            self.countInfoData = data.countInfo

            self.listMenu.forEach(el => {
              if (el.code == 'WFP') el['num'] = data.countInfo.WFP;
              if (el.code == 'YFP') el['num'] = data.countInfo.YFP;
            })

          }
        })
      },
			//获取自定义表头配置信息
			customizeHeaderDt () {
				hlhttp.get({
					url: 'configure/customize_column_header',
					data: {module: 'ZHSH_XSFP'},
					success: (data) => {
						data.customConfigList.map(item => {
							item.seq = Number(item.seq)
							item.customSeq = Number(item.customSeq)
              item.isActive = 'N'
              if (item.orderFlag == 'Y') {
                this.dateTimeUpdate.push(item.value)
              }
            })

            if (this.configType == 'JD' || this.configType == 'WZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('seq'))
              data.customConfigList.unshift({
                value: 'iSselect',
                name: '全选',
                baseFlag: 'Y',
                isChecked: 'N',
              })
            }
            if (this.configType == 'PZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('customSeq'))
              data.customConfigList.unshift({
                value: 'iSselect',
                name: '全选',
                customShowFlag: 'Y',
                isChecked: 'N'
              })
            }

            this.headArr = JSON.parse(JSON.stringify(data.customConfigList));
            this.sortTableTitle = JSON.parse(JSON.stringify(data.customConfigList));
            this.sortTableTitle.splice(0, 1)
            this.tbTitleWidthCalculation()
          }
        })
      },
      //宽度计算
      tbTitleWidthCalculation() {
        let w = 0,
          flag = false;
        this.headArr.map(item => {
          if (item.value == '序') {
            flag = true;
          }
        })
        w = this.headArr.length * 120 - 80;
        if (w < 855) {
          w = 855
        }
        this.tbTitleWidth = {
          width: w + 'px'
        }
      },
      //弹窗显示
      showTableLayer() {
        this.isShowTableLayer = true;
      },
      //关闭自定义表头弹窗
      closeTableLayer() {
        this.isShowTableLayer = false;
      },
      //简单完整配置切换
      selectTableType(type) {
        this.configType = type;
				this.changeTableType(type)
				this.updateConfigType()
      },
			//更新自定义表头配置状态
			updateConfigType () {
				hlhttp.put({
					url: 'configure/customize_column_header/type',
					data: {module: 'ZHSH_XSFP', config_type: this.configType},
					success: () => {
						this.configTypeDt()
					}
				})
			},
			//改变头部
			changeTableType (type) {
				if (type == 'JD' || type == 'WZ') {
					this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('seq'))
				}
				if (type == 'PZ') {
					this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('customSeq'))
				}
				this.tbTitleWidthCalculation()
			},
			//显示某个自定义标题
			selectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'Y'
      },
      //关闭某个自定义标题
      cancelSelectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'N'
      },
      showhighLightTitleItem(el, i) {
        this.sortTableTitle[i].isActive = 'Y'
      },
      removehighLightTitleItem(el, i) {
        this.sortTableTitle[i].isActive = 'N'
      },
      //鼠标经过显示scroll
      showScroll() {
        this.isScroll = true;
      },
      //鼠标离开关闭scroll
      hideScroll() {
        this.isScroll = false;
      },
      // 确定提交自定义表格
      confirmSubmitTable() {
        let dataArr = [];
        this.sortTableTitle.map((item, index) => {
          dataArr.push({
            "base_flag": item.baseFlag,
            "seq": item.seq,
            "custom_show_flag": item.customShowFlag,
            "custom_seq": index,
            "custom_display_name": item.customDisplayName ? item.customDisplayName : '#',
            "dict_code": item.dictCode,
            "config_type": item.configType,
            "name": item.name,
            "value": item.value,
            "union_table_part": item.unionTablePart,
            flex: item.flex,
            style_width: item.styleWidth,
            order_flag: item.orderFlag,
            order_name: item.orderName
					})
				})

				hlhttp.put({
					url: 'configure/customize_column_header',
					data: {
						module: 'ZHSH_XSFP',
						custom_config: JSON.stringify(dataArr)
					},
					success: (data) => {
						hl.toast('操作成功')
						this.closeTableLayer()
						this.updateConfigType()
					}
				})
      },
      // 初始化拖动排序
      initSortable() {
        const self = this;
        const el = document.getElementById('sortableTable');
        Sortable.create(el, {
          draggable: 'ul',
          onEnd(evt) {
            const beginIndex = evt.oldIndex;
            const endIndex = evt.newIndex;
            const newArr = JSON.parse(JSON.stringify(self.sortTableTitle));
            newArr.splice(endIndex, 0, newArr.splice(beginIndex, 1)[0])
            self.sortTableTitle = [];
            self.$nextTick(() => {
              self.sortTableTitle = newArr
            })
          }
        })
      },
			// 获取产业
			getIndustryType() {
			  hlhttp.get({
			    url: 'configure/industry/dict',
			    success: data => {
			      data.unshift({
			        'dictName': '全部',
			        'dictCode': '#'
			      })
			      this.industryType = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }]);
			    }
			  })
			},
    },
    mounted: function() {
      hlSelectUi()
			this.getIndustryType()
      this.initSortable();
      this.configTypeDt()
			this.getChannelType()
      this.search()
      this.getSJsource()
      this.getUserPositions()
    }
  })


}(window))
